<template>
  <section class="card db-card">
    <h2>数据库测试功能</h2>
    <div class="card-content">
      <div class="db-section">
        <h3>数据库信息</h3>
        <div class="info-group">
          <label>数据库路径:</label>
          <div class="path-display">
            <span>{{ dbPath || '未获取路径' }}</span>
            <button class="refresh-btn" @click="refreshDbPath" title="刷新路径">
              🔄
            </button>
          </div>
        </div>
      </div>

      <div class="db-section">
        <h3>自定义查询</h3>
        <textarea 
          v-model="query" 
          placeholder="输入SQL查询语句，例如: SELECT * FROM my_table LIMIT 10"
          class="query-input"
        ></textarea>
        <button class="primary-btn" @click="executeQuery">
          <span class="btn-icon">▶️</span>
          执行查询
        </button>
        
        <div v-if="queryResult" class="result-display">
          <h4>查询结果:</h4>
          <pre>{{ formatJSON(queryResult) }}</pre>
        </div>
        
        <div v-if="queryError" class="error-message">
          <span class="error-icon">⚠️</span>
          {{ queryError }}
        </div>
      </div>

      <div class="db-section">
        <h3>快速测试</h3>
        <div class="test-actions">
          <button class="secondary-btn" @click="insertSampleData">
            <span class="btn-icon">📝</span>
            插入测试数据
          </button>
          <button class="secondary-btn" @click="fetchData">
            <span class="btn-icon">🔍</span>
            获取所有数据
          </button>
        </div>
        
        <div v-if="testResult" class="result-display">
          <h4>操作结果:</h4>
          <pre>{{ formatJSON(testResult) }}</pre>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const dbPath = ref('');
    const query = ref('SELECT * FROM my_table LIMIT 10');
    const queryResult = ref(null);
    const queryError = ref(null);
    const testResult = ref(null);

    const formatJSON = (data) => {
      if (typeof data === 'string') return data;
      return JSON.stringify(data, null, 2);
    };

    const refreshDbPath = async () => {
      try {
        dbPath.value = await window.electronAPI.getDatabasePath();
      } catch (error) {
        dbPath.value = '获取路径失败: ' + error.message;
      }
    };

    const executeQuery = async () => {
      queryError.value = null;
      queryResult.value = null;
      
      if (!query.value.trim()) {
        queryError.value = '请输入有效的SQL语句';
        return;
      }

      try {
        const result = await window.electronAPI.queryDatabase(query.value);
        queryResult.value = result.data || result;
      } catch (error) {
        queryError.value = error.message;
      }
    };

    const insertSampleData = async () => {
      const name = `测试项 ${new Date().toLocaleString()}`;
      const value = `值 ${Math.random().toString(36).substring(2, 8)}`;
      
      try {
        const result = await window.electronAPI.executeDatabase(
          'INSERT INTO my_table (name, value) VALUES (?, ?)',
          [name, value]
        );
        testResult.value = { 
          message: '插入成功', 
          id: result.data?.id || 'N/A',
          timestamp: new Date().toISOString()
        };
      } catch (error) {
        testResult.value = { 
          error: '插入失败', 
          message: error.message 
        };
      }
    };

    const fetchData = async () => {
      try {
        const result = await window.electronAPI.queryDatabase('SELECT * FROM my_table');
        testResult.value = result.data || result;
      } catch (error) {
        testResult.value = { 
          error: '查询失败', 
          message: error.message 
        };
      }
    };

    onMounted(refreshDbPath);

    return {
      dbPath,
      query,
      queryResult,
      queryError,
      testResult,
      formatJSON,
      refreshDbPath,
      executeQuery,
      insertSampleData,
      fetchData
    };
  }
};
</script>

<style scoped>
.db-card {
  grid-column: span 2;
}

.db-section {
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.db-section:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.info-group {
  margin: 15px 0;
}

.info-group label {
  display: block;
  margin-bottom: 5px;
  color: #555;
  font-weight: 500;
}

.path-display {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.path-display span {
  flex-grow: 1;
  word-break: break-all;
}

.refresh-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.1rem;
  margin-left: 10px;
  padding: 5px;
}

.refresh-btn:hover {
  color: #3498db;
}

.query-input {
  width: 100%;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: 'Courier New', Courier, monospace;
  margin: 10px 0;
  resize: vertical;
}

.test-actions {
  display: flex;
  gap: 10px;
  margin: 15px 0;
}

.secondary-btn {
  background-color: #2ecc71;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
}

.secondary-btn:hover {
  background-color: #27ae60;
  transform: translateY(-1px);
}

.result-display {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-left: 4px solid #2ecc71;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.result-display h4 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 0.9rem;
}

.result-display pre {
  margin: 10px 0 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.error-message {
  margin-top: 15px;
  padding: 12px 15px;
  background-color: #fff5f5;
  color: #e74c3c;
  border-left: 4px solid #e74c3c;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.error-icon {
  margin-right: 8px;
  font-size: 1.2rem;
}

@media (max-width: 768px) {
  .test-actions {
    flex-direction: column;
  }
  
  .secondary-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>